package com.cfx.exercise_42;

import java.awt.BasicStroke;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Shape;
import java.awt.geom.AffineTransform;
import java.awt.geom.RoundRectangle2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.EnumMap;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.imageio.ImageIO;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.ChecksumException;
import com.google.zxing.DecodeHintType;
import com.google.zxing.EncodeHintType;
import com.google.zxing.FormatException;
import com.google.zxing.LuminanceSource;
import com.google.zxing.MultiFormatReader;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.NotFoundException;
import com.google.zxing.Reader;
import com.google.zxing.ReaderException;
import com.google.zxing.Result;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.GlobalHistogramBinarizer;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.multi.GenericMultipleBarcodeReader;
import com.google.zxing.multi.MultipleBarcodeReader;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;

/**
 * 此类生成二维码图片比较好用
 * @author zsw
 *
 */
public class QRCodeGoogleUtil {

    private static final String CHARSET = "utf-8";
    
    private static final String FORMAT_NAME = "JPG"; //二维码图片格式
    
    private static final int QRCODE_WIDTH = 50; // 二维码尺寸宽度
    
    private static final int QRCODE_HEIGHT = 50; // 二维码尺寸宽度
    
    private static final int WIDTH = 60; // LOGO宽度
    
    private static final int HEIGHT = 60; // LOGO高度

    public static BufferedImage createImage(String content, Image src, boolean needCompress) throws Exception {
		Map<EncodeHintType, Comparable<?>> hints = new HashMap<EncodeHintType, Comparable<?>>();
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
        hints.put(EncodeHintType.CHARACTER_SET, CHARSET);
        hints.put(EncodeHintType.MARGIN, 0);
        BitMatrix bitMatrix = new MultiFormatWriter().encode(content,BarcodeFormat.QR_CODE, QRCODE_WIDTH, QRCODE_HEIGHT, hints);
        int width = bitMatrix.getWidth();
        int height = bitMatrix.getHeight();
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                image.setRGB(x, y, bitMatrix.get(x, y) ? 0xFF000000 : 0xFFFFFFFF);
            }
        }
        if (src == null ) {
            return image;
        }
        insertImage(image, src, needCompress);
        return image;
    }
   
    private static void insertImage(BufferedImage source, Image src, boolean needCompress) throws Exception {
        int width = src.getWidth(null);
        int height = src.getHeight(null);
        if (needCompress) { // 压缩LOGO
            if (width > WIDTH) {
                width = WIDTH;
            }
            if (height > HEIGHT) {
                height = HEIGHT;
            }
            Image image = src.getScaledInstance(width, height, Image.SCALE_SMOOTH);
            BufferedImage tag = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
            Graphics g = tag.getGraphics();
            g.drawImage(image, 0, 0, null); // 绘制缩小后的图
            g.dispose();
            src = image;
        }
        Graphics2D graph = source.createGraphics();
        int x = (QRCODE_WIDTH - width) / 2;
        int y = (QRCODE_HEIGHT - height) / 2;
        graph.drawImage(src, x, y, width, height, null);
        Shape shape = new RoundRectangle2D.Float(x, y, width, width, 6, 6);
        graph.setStroke(new BasicStroke(3f));
        graph.draw(shape);
        graph.dispose();
    }
   
    /**
     * 生成二维码图片
     * 
     * @param content 内容
     * @param imgInput 包含的logo图片输入流
     * @param output  生成的二维码图片文件输出流
     * @throws Exception
     */
    public static void encode(String content, OutputStream output, InputStream imgInput) throws Exception {
    	Image src = ImageIO.read(imgInput);
    	BufferedImage image = createImage(content, src, true);
    	ImageIO.write(image, FORMAT_NAME, output);
    }
    
   /**
    * 生成二维码图片
    * 
    * @param content 内容 
    * @param output  生成的二维码图片文件输出流
    * @throws Exception
    */
    public static void encode(String content, OutputStream output) throws Exception {
    	BufferedImage image = createImage(content, null, false);
    	ImageIO.write(image, FORMAT_NAME, output);
    }
    
    /*private static String decode(BufferedImage image) throws Exception {
    	BufferedImageLuminanceSource source = new BufferedImageLuminanceSource(image);
    	BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
    	Map<DecodeHintType, Object> hints = new HashMap<DecodeHintType, Object>();
    	hints.put(DecodeHintType.CHARACTER_SET, CHARSET);
    	hints.put(DecodeHintType.TRY_HARDER, Boolean.TRUE);
    	hints.put(DecodeHintType.PURE_BARCODE, Boolean.TRUE);
    	hints.put(DecodeHintType.POSSIBLE_FORMATS,
    	        EnumSet.allOf(BarcodeFormat.class));
    	hints.put(DecodeHintType.ALLOWED_EAN_EXTENSIONS, Boolean.TRUE);
    	Result result = new MultiFormatReader().decode(bitmap, hints);
//    	Result result = new QRCodeReader().decode(bitmap, hints);
    	return result.getText();
    }*/
    
	@SuppressWarnings("unused")
	private static String encode(BufferedImage image)
			throws Exception {
		String result = null;
		LuminanceSource source = new BufferedImageLuminanceSource(image);
		BinaryBitmap bitmap = new BinaryBitmap(new GlobalHistogramBinarizer(source));
		List<Result> results = new ArrayList<>(1);
		Map<DecodeHintType,Object> HINTS = new EnumMap<>(DecodeHintType.class);
		HINTS.put(DecodeHintType.TRY_HARDER, Boolean.TRUE);
	    HINTS.put(DecodeHintType.POSSIBLE_FORMATS, EnumSet.allOf(BarcodeFormat.class));
	    Map<DecodeHintType,Object> HINTS_PURE = new EnumMap<>(HINTS);
	    HINTS_PURE.put(DecodeHintType.PURE_BARCODE, Boolean.TRUE);
		try {

			Reader reader = new MultiFormatReader();
			ReaderException savedException = null;
			try {
				// Look for multiple barcodes
				MultipleBarcodeReader multiReader = new GenericMultipleBarcodeReader(
						reader);
				Result[] theResults = multiReader.decodeMultiple(bitmap, HINTS);
				if (theResults != null) {
					results.addAll(Arrays.asList(theResults));
				}
			} catch (ReaderException re) {
				savedException = re;
			}
			if (results.isEmpty()) {
				try {
					// Look for pure barcode
					Result theResult = reader.decode(bitmap, HINTS_PURE);
					if (theResult != null) {
						results.add(theResult);
					}
				} catch (ReaderException re) {
					savedException = re;
				}
			}
			if (results.isEmpty()) {
				try {
					// Look for normal barcode in photo
					Result theResult = reader.decode(bitmap, HINTS);
					if (theResult != null) {
						results.add(theResult);
					}
				} catch (ReaderException re) {
					savedException = re;
				}
			}
			if (results.isEmpty()) {
				try {
					// Try again with other binarizer
					BinaryBitmap hybridBitmap = new BinaryBitmap(
							new HybridBinarizer(source));
					Result theResult = reader.decode(hybridBitmap, HINTS);
					if (theResult != null) {
						results.add(theResult);
					}
				} catch (ReaderException re) {
					savedException = re;
				}
			}
			if (results.isEmpty()) {
				try {
					throw savedException == null ? NotFoundException
							.getNotFoundInstance() : savedException;
				} catch (FormatException | ChecksumException e) {
					e.printStackTrace();
//				} catch (ReaderException e) { // Including NotFoundException
//					e.printStackTrace();
				}
				return null;
			}
		} catch (RuntimeException re) {
			// Call out unexpected errors in the log clearly
			throw re;
		}
//		for (Result result1 : results) {
//			result += result1.getText();
//		}
		if(results.size() > 0){
			result = results.get(0).getText();
		}
		return result;
	}
	private static String encode2(BufferedImage image) throws Exception {
		LuminanceSource source = new BufferedImageLuminanceSource(image);
		BinaryBitmap bitmap = new BinaryBitmap(new GlobalHistogramBinarizer(source));
		Result result = null;
		Map<DecodeHintType,Object> HINTS = new EnumMap<>(DecodeHintType.class);
		HINTS.put(DecodeHintType.TRY_HARDER, Boolean.TRUE);
		HINTS.put(DecodeHintType.POSSIBLE_FORMATS, EnumSet.allOf(BarcodeFormat.class));
		Map<DecodeHintType,Object> HINTS_PURE = new EnumMap<>(HINTS);
		HINTS_PURE.put(DecodeHintType.PURE_BARCODE, Boolean.TRUE);
		try {
			
			Reader reader = new MultiFormatReader();
			ReaderException savedException = null;
				try {
					// Look for pure barcode
					result = reader.decode(bitmap, HINTS_PURE);
				} catch (ReaderException re) {
					savedException = re;
				}
			if (result == null) {
				try {
					// Look for normal barcode in photo
					result = reader.decode(bitmap, HINTS);
				} catch (ReaderException re) {
					savedException = re;
				}
			}
			if (result == null) {
				try {
					// Try again with other binarizer
					BinaryBitmap hybridBitmap = new BinaryBitmap(
							new HybridBinarizer(source));
					result = reader.decode(hybridBitmap, HINTS);
				} catch (ReaderException re) {
					savedException = re;
				}
			}
			if (result == null) {
				try {
					throw savedException == null ? NotFoundException
							.getNotFoundInstance() : savedException;
				} catch (FormatException | ChecksumException e) {
					e.printStackTrace();
				}
				return null;
			}
		} catch (RuntimeException re) {
			// Call out unexpected errors in the log clearly
			throw re;
		}
		return result.getText();
	}
    
   /**
    * 将二维码解析成对应内容
    * 
    * @param path 图片路径
    * @return
    * @throws Exception
    */
	public static String decode(String path) throws Exception {
        BufferedImage image = ImageIO.read(new File(path));
        if (image == null) {
            return null;
        }
        return encode2(image);
    }
    
    /**
     * 将二维码解析成对应内容
     *  
     * @param input 图片输入流
     * @return
     * @throws IOException 
     * @throws Exception
     */
    public static String decode(InputStream input) throws Exception  {
    	BufferedImage image = ImageIO.read(input);
    	if (image == null) {
    		return null;
    	}
    	return encode2(image);
    }
    private static class BufferedImageLuminanceSource extends LuminanceSource {
        private final BufferedImage image;
        private final int left;
        private final int top;

        public BufferedImageLuminanceSource(BufferedImage image) {
            this(image, 0, 0, image.getWidth(), image.getHeight());
        }

        public BufferedImageLuminanceSource(BufferedImage image, int left,
                int top, int width, int height) {
            super(width, height);
            int sourceWidth = image.getWidth();
            int sourceHeight = image.getHeight();
            if (left + width > sourceWidth || top + height > sourceHeight) {
                throw new IllegalArgumentException( "Crop rectangle does not fit within image data.");
            }
            for (int y = top; y < top + height; y++) {
                for (int x = left; x < left + width; x++) {
                    if ((image.getRGB(x, y) & 0xFF000000) == 0) {
                        image.setRGB(x, y, 0xFFFFFFFF); // = white
                    }
                }
            }
            this.image = new BufferedImage(sourceWidth, sourceHeight, BufferedImage.TYPE_BYTE_GRAY);
            this.image.getGraphics().drawImage(image, 0, 0, null);
            this.left = left;
            this.top = top;
        }

        public byte[] getRow(int y, byte[] row) {
            if (y < 0 || y >= getHeight()) {
                throw new IllegalArgumentException("Requested row is outside the image: " + y);
            }
            int width = getWidth();
            if (row == null || row.length < width) {
                row = new byte[width];
            }
            image.getRaster().getDataElements(left, top + y, width, 1, row);
            return row;
        }
       
        public byte[] getMatrix() {
            int width = getWidth();
            int height = getHeight();
            int area = width * height;
            byte[] matrix = new byte[area];
            image.getRaster().getDataElements(left, top, width, height, matrix);
            return matrix;
        }
       
        public boolean isCropSupported() {
            return true;
        }
       
        public LuminanceSource crop(int left, int top, int width, int height) {
            return new BufferedImageLuminanceSource(image, this.left + left, this.top + top, width, height);
        }

        public boolean isRotateSupported() {
            return true;
        }

        public LuminanceSource rotateCounterClockwise() {
            int sourceWidth = image.getWidth();
            int sourceHeight = image.getHeight();
            AffineTransform transform = new AffineTransform(0.0, -1.0, 1.0, 0.0, 0.0, sourceWidth);
            BufferedImage rotatedImage = new BufferedImage(sourceHeight, sourceWidth, BufferedImage.TYPE_BYTE_GRAY);
            Graphics2D g = rotatedImage.createGraphics();
            g.drawImage(image, transform, null);
            g.dispose();
            int width = getWidth();
            return new BufferedImageLuminanceSource(rotatedImage, top, sourceWidth - (left + width), getHeight(), width);
        }
    }
}